package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class UploadImgServlet
 */
@WebServlet("/UploadImgServlet2")
public class UploadImgServlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadImgServlet2() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println(request.getParameter("goodId"));
		//获取服务器中项目根目录
		String savePath =     
				  request.getServletContext().getRealPath("/postImg");
		java.io.File uploadDir = new java.io.File(savePath);
		//如果此目录不存在，新建该目录
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        
		//新建一个SmartUpload，因form使用了multipart/form-data
		//所以值变成二进制数据，request无法获取，故需要用此类获取值
		SmartUpload su = new SmartUpload();
		 // 上传初始化
		  su.initialize(this.getServletConfig(),request,response);
		try {
			  // 上传文件
			  su.upload();
		} catch (SmartUploadException e) {
			System.out.println(e.getMessage());
		}
		
		//保存上传
		 if (!su.getFiles().getFile(0).isMissing()) {
			  try {
				su.save(savePath);
			} catch (SmartUploadException e) {
				System.out.println(e.getMessage());
			}
		  }
		 
		 Map<String, Object> map = new HashMap<String, Object>();
		 map.put("success", "成功啦");
		//将json所需的包放到lib里面,将list转换为json
		//如果只是一个对象用JSONObject，如果是集合用JSONArray
        JSONObject json=JSONObject.fromObject(map);
        
        //响应前台页面
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json");
        PrintWriter out=response.getWriter();
        out.println(json);//打印json，为了前台页面获取
        out.flush();//刷新流
        out.close();//关闭流

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
